package com.sishu.njrtsdms.validate;

import com.sishu.njrtsdms.annotation.ValidDateTime;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class DateTimeValidator
        implements ConstraintValidator<ValidDateTime, LocalDateTime> {
    private String pattern;

    @Override
    public void initialize(ValidDateTime constraintAnnotation) {
        this.pattern = constraintAnnotation.pattern();
    }

    @Override
    public boolean isValid(LocalDateTime value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            formatter.format(value);
            return true;
        } catch (DateTimeParseException e) {
            return false;
        }
    }
}
